package com.etcn.common.utils.http;

import java.io.ByteArrayOutputStream;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import com.etcn.common.utils.JsonHandler;
import com.etcn.common.utils.datacompress.GZIPUtil;

/**
 * Http请求数据传输辅助类
 * @author: guozc
 * @date: 2016-08-03
 */
public class HttpTransfer {

	/**
	 * 从HttpServletRequest对象中解析参数并转为字符串(能够接收json参数和二进制参数)
	 * @param HttpServletRequest
	 * @return 字符串
	 * @throws Exception
	 */
	public static String fetchString(HttpServletRequest request) throws Exception{
		String data = null;
		ServletInputStream in = request.getInputStream();  
        String contentEncoding = request.getHeader("Content-Encoding");
        //gzip压缩的
        if (contentEncoding != null && contentEncoding.indexOf("gzip") != -1) {
        	data = GZIPUtil.unCompress(in);
        }
        //未压缩
        else{
        	ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        	byte[] buffer = new byte[1024];
        	int len = 0;
        	while((len = in.read(buffer)) != -1){
        		outStream.write(buffer, 0, len);
        	}
        	data = outStream.toString(request.getCharacterEncoding());
        }
        return data;
	}
	
	/**
	 * 从HttpServletRequest对象中解析参数并转为对象(能够接收json参数和二进制参数)
	 * @param HttpServletRequest
	 * @param type 对象类型
	 * @return 对象
	 * @throws Exception
	 */
	public static <T> T fetchObject(HttpServletRequest request,Class<T> type) throws Exception{
		String str = fetchString(request);
		return JsonHandler.build().toObject(str, type);
	}
}
